import logger from '../core/logger';
import channelFeed from '../model/other/channelFeed';
import regionModel from '../model/other/regionModel';
import returnModel from '../model/common/returnModel';
import apiInfo from './core/apiInfo';
import { clientBase } from './core/clientBase';

export class channelClient extends clientBase {
  constructor() {
    super();
  }

  getRank(rid: number, type: string): Promise<returnModel<any>> {
    var self = this;
    return new Promise((resolve) => {
      try {
        let info = new apiInfo("https://api.bilibili.com/x/web-interface/ranking/v2", `&rid=${rid}&type=${type.toLowerCase()}`, null, false);
        this.client.getResult(info).then((res) => {
          resolve(self.buildSuccessResult<any>(res));
        });
      } catch (e) {
        logger.error(e);
        resolve(this.buildExceptionResult<any>(e));
      }
    });
  }

  setRegions(): Promise<returnModel<regionModel>> {
    var self = this;
    return new Promise((resolve) => {
      try {
        let info = new apiInfo("https://app.bilibili.com/x/v2/region/index", '', null, false);
        this.client.getResult(info).then((res) => {
          var data: regionModel = res;
          resolve(self.buildSuccessResult<regionModel>(data));
        });
      } catch (e) {
        logger.error(e);
        resolve(this.buildExceptionResult<regionModel>(e));
      }
    });
  }

  getChannelFeeds(channel_id: string, name: string, page: number): Promise<returnModel<Array<channelFeed>>> {
    var self = this;
    return new Promise((resolve) => {
      try {
        let info = new apiInfo("https://app.bilibili.com/x/channel/feed", `&channel_id=${channel_id}&channel_name=${encodeURIComponent(name)}&display_id=${page}&login_event=0&pull=${(page == 1).toString().toLowerCase()}`, null, true);
        this.client.getResult(info).then((res) => {
          if (res.code == 0) {
            let info: Array<regionModel> = res.data.feed;
            resolve(self.buildSuccessResult<Array<regionModel>>(info));
          } else {
            resolve(self.buildFailedResult<Array<regionModel>>(res.message));
          }
        });
      } catch (e) {
        logger.error(e);
        resolve(this.buildExceptionResult<Array<channelFeed>>(e));
      }
    });
  }
}

export default new channelClient();